//
//  MomentumView.m
//  LottieAnimationTest
//
//  Created by Felix Yin on 2019/7/17.
//  Copyright © 2019 Felix Yin. All rights reserved.
//

#import "MomentumView.h"
#import "UIView+Layout.h"
#import "POP.h"

@interface MomentumView ()



@end

@implementation MomentumView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UIPanGestureRecognizer *ges = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
        [self addGestureRecognizer:ges];
    }
    return self;
}

//    MARK: Animation Handle

- (void) startAnimation:(UIPanGestureRecognizer *) ges{
    CGFloat centerY = 0;
    CGFloat minCenterY = self.height*0.5 + self.minTopOffset;
    CGFloat maxCenterY = self.height*0.5 + self.maxTopOffset;
    if (self.centerY < minCenterY) {
        centerY = minCenterY;
    }else if(self.centerY > maxCenterY){
        centerY = maxCenterY;
    }else{
        centerY = self.superview.centerY > self.top ? minCenterY : maxCenterY;
    }
    [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:0.3 options:UIViewAnimationOptionCurveLinear animations:^{
        self.centerY = centerY;
    } completion:^(BOOL finished) {
        
    }];
    
    
    /*
     
     使用POP 框架实现
     
     */
    
    //    POPSpringAnimation *animation = [POPSpringAnimation animationWithPropertyNamed:kPOPViewCenter];
    //    animation.springSpeed = 10; // 速度
    //    animation.springBounciness = 0.1;//弹力
    //    animation.dynamicsFriction = 30;//
    //    animation.dynamicsMass = 1;
    //    animation.toValue = [NSValue valueWithCGPoint:CGPointMake(self.centerX, centerY)];
    //    [self pop_addAnimation:animation forKey:@"POPSpringAnimation"];
    
}

- (void) cancleAnimation:(UIPanGestureRecognizer *) ges{
    /*
     
     使用POP 框架实现
     
     */
    //    if (self.pop_animationKeys.count > 0) {
    //        [self pop_removeAllAnimations];
    //    }
}

//    MARK: Gesture Handle

- (void) panGesture:(UIPanGestureRecognizer *) ges{
    CGFloat gesY = self.top + [ges translationInView:self.superview].y;
    if (gesY > self.maxTopOffset) {
        gesY = self.maxTopOffset;
    }else if (gesY < self.minTopOffset){
        gesY = self.minTopOffset;
    }
    self.top = gesY;
    [ges setTranslation:CGPointZero inView:self.superview];//重置手势位置信息
    if (ges.state == UIGestureRecognizerStateBegan) {
        //移除动画
        [self cancleAnimation:ges];
    }else if(ges.state == UIGestureRecognizerStateEnded){
        //动画开始
        [self startAnimation:ges];
    }
}


@end
